//
//  YCLoadOAuthVC.swift
//  weiBoSwift
//
//  Created by 刘胤辰 on 16/7/21.
//  Copyright © 2016年 it.com. All rights reserved.
//

import UIKit
import AFNetworking

class YCLoadOAuthVC: UIViewController {
    
    private lazy var progressView:YCProgressView=YCProgressView()
    
    private lazy var webView:UIWebView=UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        view.backgroundColor=UIColor.whiteColor()
        let url=NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)")
        let str="https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        print(str)
        guard let u=url else{
            return
        }
        
        webView.loadRequest(NSURLRequest(URL: u))
        
        //设置代理
        webView.delegate=self
        
        view=webView
        
        //设置界面
        setUI()
    }
    
    func setUI(){
        
        title="微博登录"
        let autoFillItem=YCBarItem(title: "自动填充", imageName: nil, target: self, action: "clickFillAuto")
        let cancleItem=YCBarItem(title: "取消", imageName: nil, target: self, action: "clickCancle")
        
        navigationItem.rightBarButtonItem=autoFillItem
        navigationItem.leftBarButtonItem=cancleItem
        
        //添加进度条
        view.addSubview(progressView)
        
        //设置约束  此处设置约束会报错
//        progressView.snp_makeConstraints { (make) -> Void in
//            
//            make.top.equalTo(view).offset(64)
//            make.left.equalTo(view).offset(0)
//            make.right.equalTo(view).offset(0)
//            make.width.equalTo(2)
//        }
    }
    
    @objc private func clickFillAuto(){
        
        let string="document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        webView .stringByEvaluatingJavaScriptFromString(string)
        
    }
    
    @objc private func clickCancle(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
}

extension YCLoadOAuthVC : UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 请求的url字符串
        let urlString = request.URL?.absoluteString
        // 判断urlString 是否为nil 而且他的前缀为回调页
        if let u = urlString where u.hasPrefix(APPREDIRECT_URI) {
            // url 的请求参数
            let query = request.URL?.query
            if let q = query {
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
                print("终于等到你还好没放弃:\(code)")
                
                //自己的思路
//               YCNetWorkTools.shareTools.getOauthData(code, success: { (success) -> () in
//                print("++++++++++++++++++成功")
//                print(success)
//                }, falure: { (error) -> () in
//                print("++++++++++++++++++失败")
//                print(error)
//               })
                //老师的思路
                SHUserAccountViewModel.sharedTools.loadUserAccountData(code, isSuccess: { (isSuccess) -> () in
                    
                    if isSuccess == false {
//                        print("fasfafasdfdasfasfa")
                        return
                    }
                    
                    //然后进行关闭跳转的百度页面
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
                        //更改根控制器(跳到欢迎界面)
                        NSNotificationCenter.defaultCenter().postNotificationName("changeVC", object: nil)
                        
                    })
                    
                })
                
                
            }
        }
        return true
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        progressView.stopAnimination()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        progressView.startAnimination()

    }
}
